# coding: utf-8
# 文件名称: 斗图啦_spider.py
# 创建时间: 2021/6/20 20:49

import requests
from lxml import etree
import os
import re
from urllib import request
from queue import Queue
import threading

class Procuder(threading.Thread):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48'
    }
    def __init__(self, page_queue, img_queue, *args, **kwargs):
        super(Procuder, self).__init__(*args, **kwargs)
        self.page_queue = page_queue
        self.img_queue = img_queue

    def run(self):
        while True:
            if self.page_queue.empty():
                break
            url = self.page_queue.get()
            self.parse_page(url)


    def parse_page(self, url):
        print(url)

        response = requests.get(url, headers=self.headers)
        text = response.text
        # 构建lxml
        html = etree.HTML(text)

        # 获取所有目标的img标签，过滤class为gif的img
        imgs = html.xpath('//div[@class="page-content text-center"]//img[@class != "gif"]')
        for img in imgs:
            # 获取图片地址，有2种方式
            # img_url = img.xpath('.//@data-original')
            img_url = img.get('data-original')

            # 构建图片名称
            # 拆解原文件路径
            old_name = os.path.split(img_url)[1]
            new_name = '../images/' + old_name

            self.img_queue.put((img_url, new_name))

class Consumer(threading.Thread):
    def __init__(self, page_queue, img_queue, *args, **kwargs):
        super(Consumer, self).__init__(*args, **kwargs)
        self.page_queue = page_queue
        self.img_queue = img_queue


    def run(self):
        while True:
            print('消费者=', self.img_queue.empty() , self.page_queue.empty())
            if self.img_queue.empty() and self.page_queue.empty():
                break
            img_url, filename = self.img_queue.get()
            # 把图片下载到本地
            # request.urlretrieve(img_url, filename)
            print(f'{filename} 下载完成！')

def main():
    page_queue = Queue(10)
    img_queue = Queue(1000)
    for i in range(1,11):
        url = f'https://www.doutula.com/photo/list/?page={i}'
        print(url)
        page_queue.put(url)

    for x in range(5):
        t = Procuder(page_queue, img_queue)
        t.start()

    for x in range(5):
        print('main=', img_queue.empty())
        t = Consumer(page_queue, img_queue)
        t.start()

if __name__ == '__main__':
    main()
